import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, Card, Select, Space, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import {
  IhospitalList,
  IhospitalItem,
  IdictList,
} from '@api/hospital/hospitalList/model/hospitalListTypes'
import {
  reqHospitalList,
  reqProvinceList,
  reqCityOrDistrictList,
  reqUpdateHosStatus,
} from '@api/hospital/hospitalList'
import './index.css'
const { Option } = Select

let flag = false // 判断是否需要添加筛选条件查询表格数据的依据
export default function HospitalList() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])

  // 分页相关的状态
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)

  const [loading, setLoading] = useState(false)

  // 省,市,区三级数据
  const [province, setProvince] = useState<IdictList>([])
  const [city, setCity] = useState<IdictList>([])
  const [district, setDistrict] = useState<IdictList>([])
  // 医院类型数据
  const [hostypes, setHostypes] = useState<IdictList>([])

  useEffect(() => {
    // 获取表格数据
    getHospitalList(page, pageSize)
    // 获取省数据
    getProvince()
    // 获取医院类型
    getHosTypes()
  }, [])

  //获取医院列表数据的方法
  async function getHospitalList(page: number, pageSize: number) {
    setLoading(true)
    // 判断
    let result
    if (flag) {
      // 添加筛选条件
      const data = form.getFieldsValue()

      // {...data} ==> {hosname:data.hosname,}
      // 直接将data展示,实现的效果就是hosname:data.hosname这样的效果
      result = await reqHospitalList({ page, limit: pageSize, ...data })
    } else {
      // 不添加筛选条件
      result = await reqHospitalList({ page, limit: pageSize })
    }

    setLoading(false)
    setHospitalList(result.content)
    setTotal(result.totalElements)
  }

  // 获取省数据的函数
  async function getProvince() {
    const result = await reqProvinceList()
    setProvince(result)
  }

  // 获取

  // 查询按钮的事件处理函数
  const onFinish = (values: any) => {
    // console.log('Success:', values)
    flag = true
    getHospitalList(1, pageSize)
    setPage(1)
  }

  // 选中了某个省触发的函数,获取市数据
  async function getCity(value: string) {
    //   发送请求,获取市数据
    const result = await reqCityOrDistrictList(value)
    setCity(result)
    // 清除市和区的数据
    form.setFieldsValue({ cityCode: '', districtCode: '' })
  }

  // 选中了某个市触发的函数,获取区数据
  async function getDistrict(value: string) {
    //   发送请求,获取市数据
    const result = await reqCityOrDistrictList(value)
    setDistrict(result)
    // 清除区的数据
    form.setFieldsValue({ districtCode: '' })
  }

  // 获取医院类型数据
  async function getHosTypes() {
    //   发送请求,获取市数据
    const result = await reqCityOrDistrictList('10000')
    setHostypes(result)
  }

  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',
      align: 'center',
      render: (a, b, index) => index + 1,
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render(logo) {
        return <img src={'data:image/png;base64,' + logo} alt="" width="80" />
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(data) {
        return data.param.hostypeString
      },
    },
    {
      title: '详细地址',
      render(data) {
        return data.param.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 200,

      render: (record) => (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              navigate(`/syt/hospital/HospitalList/detail/${record.id}`)
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            onClick={() => {
              navigate(`/syt/hospital/HospitalList/schedule/${record.hoscode}`)
            }}
          >
            排班
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              // 发送请求修改医院状态
              await reqUpdateHosStatus(record.id, record.status ? 0 : 1)
              // 更新表格数据
              getHospitalList(page, pageSize)
            }}
          >
            {record.status ? '下线' : '上线'}
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <Card>
      <Form
        onFinish={onFinish}
        layout="inline"
        form={form}
        onValuesChange={() => {
          flag = false
        }}
      >
        <Form.Item name="provinceCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择省"
            className="space"
            onChange={getCity}
          >
            {province.map((item) => (
              <Option key={item.id} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择市"
            className="space"
            onChange={getDistrict}
          >
            {city.map((item) => (
              <Option key={item.id} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择区"
            className="space"
          >
            {district.map((item) => (
              <Option key={item.id} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" className="space" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编码" className="space" />
        </Form.Item>

        <Form.Item name="hostype">
          <Select
            style={{ width: 200 }}
            placeholder="医院类型"
            className="space"
          >
            {hostypes.map((item) => (
              <Option key={item.id} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            style={{ width: 200 }}
            placeholder="医院状态"
            className="space"
          >
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Space className="space">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button
              onClick={() => {
                flag = false
                getHospitalList(1, pageSize)
                setPage(1)
                // 清空表单中所有表单元素的值
                // form.setFieldsValue({})
                // 利用重置表单,实现清空表单的效果.因为当前表单初始值都为空
                form.resetFields()
              }}
            >
              清空
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Table
        rowKey={'id'}
        loading={loading}
        columns={columns}
        dataSource={hospitalList}
        pagination={{
          total,
          pageSize,
          current: page,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          showQuickJumper: true,
          showTotal() {
            return `总共:${total}条`
          },
          onChange(page, pageSize) {
            setPage(page)
            setPageSize(pageSize)
            getHospitalList(page, pageSize)
          },
        }}
      />
    </Card>
  )
}
